package com.mmall.seckill.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类
 * Created by megan on 2018/1/1.
 */
@Slf4j
public class CookieUtil {
    private final static String COOKIE_DOMAIN = PropertiesUtil.getProperty("cookie.domain","localhost");
    private final static String COOKIE_NAME = "seckill_login_token";

    /**
     * 读取cookie
     * @param request
     * @return
     */
    public static String readLoginToken(HttpServletRequest request){
        Cookie[] cks = request.getCookies();
        if(cks !=null){
            for(Cookie ck : cks ){
                log.info("read coolkieName={},cookieValue:{}",ck.getName(),ck.getValue());
                if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    log.info("return cookieName{},cookieValue:{}",ck.getName(),ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 写入cookie
     * @param response
     * @param token
     */
    public static void writrLoginToken(HttpServletResponse response, String token){
        Cookie ck = new Cookie(COOKIE_NAME,token);
        ck.setDomain(COOKIE_DOMAIN);
        ck.setPath("/");//代表设置在跟目录
        ck.setHttpOnly(true);
        //单位秒
        //如果这个maxage不设置的话,cookie就不会写入磁盘,而是写在内存。只在当前页面有效
        ck.setMaxAge(60 * 60 * 24 * 356);//(一年)如果是-1,代表永久有效
        log.info("write cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
        response.addCookie(ck);
    }
    /**
     * 写入cookie
     * @param response
     * @param token
     */
    public static void writrLoginTokenEx(HttpServletResponse response, String  token,int ex){
        Cookie ck = new Cookie(COOKIE_NAME,token);
        ck.setDomain(COOKIE_DOMAIN);
        //如果这个maxage不设置的话,cookie就不会写入磁盘,而是写在内存。只在当前页面有效
        ck.setMaxAge(ex);
        ck.setPath("/");//代表设置在跟目录
        ck.setHttpOnly(true);
        //单位秒
        log.info("write cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
        response.addCookie(ck);
    }

    /**
     * 删除cookie
     * @param request
     * @param response
     */
    public static void delLoginToken(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cks = request.getCookies();
        if(cks != null){
            for(Cookie ck : cks){
                if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    ck.setDomain(COOKIE_DOMAIN);
                    ck.setPath("/");
                    ck.setMaxAge(0);//设置成0，代表删除此cookie。
                    log.info("del cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }
}
